package com.globaleducation365.tvshows.view;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.baby.tv.R;
import com.bzydroid.network.http.NetworkResponse;
import com.bzydroid.network.http.client.BzydroidHttpClient;
import com.bzydroid.network.http.exception.BzydroidNetworkExeception;
import com.bzydroid.network.http.response.HttpJSONObjectResponse;
import com.globaleducation365.tvshows.E4KidsConfig;
import com.globaleducation365.tvshows.E4KidsSlidingMenuActivity;
import com.globaleducation365.tvshows.adapter.ItemVideoRelativeAdapter;
import com.globaleducation365.tvshows.customize.BaseRequestHandler;
import com.globaleducation365.tvshows.entity.InfoVideo;
import com.globaleducation365.tvshows.service.RequestService;
import com.globaleducation365.tvshows.util.Debug;
import com.globaleducation365.tvshows.util.Util;

public class ListVideoByPlaActivity extends E4KidsSlidingMenuActivity implements
	OnClickListener {
    private ListView lvVideo;
    private LinearLayout llLoading;
    private LinearLayout llNotInternet;
    private ItemVideoRelativeAdapter adapter;

    private boolean isLoading;
    private RequestVideoNew requestVideoNew;

    private int page = 1;

    private ImageView ivABCancelSearch;
    private ImageView ivABSearch;
    private EditText edtABSearch;
    private LinearLayout llContainEdt;
    private TextView tvABTitle;
    private LinearLayout llLoadingFooter;
    private String aId;
    private TextView tvNoData;
    private ImageView ivABLogo;

    @Override
    public void onCreate(Bundle arg0) {
	super.onCreate(arg0);
	this.setContentView(R.layout.activity_list_relative);
	this.setBehindContentView(R.layout.frame_layout_container);
	// this.getSlidingMenu().setSecondaryMenu(R.layout.frame_right_container);
	this.setDefaultBar();
	configLeftSlideMenu();
	// this.removeSlidingMenu();

	init();
    }

    private void init() {
	Bundle bundle = getIntent().getExtras();

	if (bundle != null) {
	    aId = bundle.getString(E4KidsConfig.KEY_INTENT_AID);

	    Debug.debug("ListVideoByPlaActivity : " + aId);
	}



	ivABCancelSearch = actionBar.getIvABCancelSearch();
	ivABSearch = actionBar.getIvABSearch();
	edtABSearch = actionBar.getEdtABSearch();
	llContainEdt = actionBar.getLlContainEdt();
	ivABLogo = actionBar.getIvABLogo();
	tvABTitle = actionBar.getTvABTitle();

	ivABLogo.setOnClickListener(new OnClickListener() {

	    @Override
	    public void onClick(View arg0) {
		onBackPressed();
	    }
	});

	// edtABSearch.setOnEditorActionListener(searchAction);
	ivABSearch.setOnClickListener(this);
	ivABCancelSearch.setOnClickListener(this);

	edtABSearch.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
	edtABSearch.setOnEditorActionListener(new OnEditorActionListener() {

	    @Override
	    public boolean onEditorAction(TextView arg0, int actionID,
		    KeyEvent arg2) {
		// RequestUrlService.requestSearchNameSinger(delegateSinger,
		// "tuan hung");
		String text = edtABSearch.getText().toString().trim();
		if (!text.equals("") || !TextUtils.isEmpty(text)) {
		   
		    goActivitySearch(ListVideoByPlaActivity.this,SearchResultActivity.class, E4KidsConfig.KEY_INTENT_SEARCH, text);
		}
		return true;
	    }
	});

	lvVideo = (ListView) findViewById(R.id.lvRelative);

	tvNoData = (TextView) findViewById(R.id.tvNoData);

	LayoutInflater inflater = getLayoutInflater();
	View header = inflater.inflate(R.layout.layout_header, null);
	View footer = inflater.inflate(R.layout.layout_footer, null);

	llLoadingFooter = (LinearLayout) footer
		.findViewById(R.id.llLoadingFooter);

	lvVideo.addHeaderView(header);
	lvVideo.addFooterView(footer);

	llLoading = (LinearLayout) findViewById(R.id.ll_loading);
	llNotInternet = (LinearLayout) findViewById(R.id.llNoInternet);

	adapter = new ItemVideoRelativeAdapter(ListVideoByPlaActivity.this,
		imageLoader, options);

	// idCat = String.valueOf(application.getCatID());

	// if(idCat.equals("") || idCat.equals("0")|| idCat.equals("-1"))
	// {
	// idCat = "0";
	// }
	//
	// Debug.debug("CatId New Video : " + idCat);

	loadMore();
	lvVideo.setAdapter(adapter);

	if (lvVideo.isSmoothScrollbarEnabled()) {
	    Debug.debug("Keo duoc listview");
	} else {
	    Debug.debug("Khong Keo duoc listview");
	}


	 lvVideo.setOnItemClickListener(new OnItemClickListener() {
		    @Override
		    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
			    long arg3) {
			InfoVideo infoVideo = adapter.getItem(arg2);
			if (infoVideo != null) {
			    Bundle bundle = new Bundle();

			    bundle.putString(E4KidsConfig.KEY_INTENT_VID,
				    infoVideo.getVid());
			    bundle.putString(E4KidsConfig.KEY_INTENT_LINK,
				    infoVideo.getvYoutube());

			    goActivitySearch(ListVideoByPlaActivity.this,
				    PlayVideo.class, bundle);
			}

		    }
		});

	lvVideo.setOnScrollListener(new OnScrollListener() {

	    @Override
	    public void onScrollStateChanged(AbsListView arg0, int arg1) {

	    }

	    @Override
	    public void onScroll(AbsListView arg0, int arg1, int arg2, int arg3) {
		if ((arg1 + arg2) == arg3 && isLoading) {
		    isLoading = false;
		    page = page + 1;

		    llLoadingFooter.setVisibility(View.VISIBLE);

		    loadMore();

		    Debug.debug("Page New: " + page);
		}
	    }
	});
    }

    private class RequestVideoNew extends BaseRequestHandler {
	public RequestVideoNew(Activity context, OnClickListener clickTry) {
	    super(context, clickTry);
	}

	@Override
	public void onWait(BzydroidHttpClient arg0) {
	    super.onWait(arg0);
	}

	@Override
	public void onStarted(BzydroidHttpClient arg0) {
	    super.onStarted(arg0);
	    Debug.debug("onStarted");
	}

	@Override
	public void onSuccess(BzydroidHttpClient arg0, NetworkResponse arg1) {

	    // Debug.debug("Danh sach : " + a);
	    HttpJSONObjectResponse jsonObjectResponse = (HttpJSONObjectResponse) arg0
		    .getResponse();
	    try {
		JSONObject object = jsonObjectResponse.toJSONObject();
		//
		Debug.debug("Danh sach : " + object.toString());

		JSONObject jObjData = object
			.getJSONObject(E4KidsConfig.KEY_DATA);

		int code = jObjData.getInt(E4KidsConfig.KEY_CODE);

		if (code == 1) {
		    Debug.debug("Con du lieu");

		    isLoading = true;

		    JSONArray jArrVideo = jObjData
			    .getJSONArray(E4KidsConfig.ListViewNew.KEY_VIDEO);

		    int length = jArrVideo.length();

		    for (int i = 0; i < length; i++) {
			JSONObject jObj = jArrVideo.getJSONObject(i);

			InfoVideo infoVideo = parseJsonVideo(jObj);

			adapter.addData(infoVideo);
		    }
		    lvVideo.setVisibility(View.VISIBLE);
		} else {

		    Debug.debug("Het du lieu");
		    isLoading = false;
		    if (adapter.getCount() <= 0) {
			tvNoData.setVisibility(View.VISIBLE);
			lvVideo.setVisibility(View.GONE);
			llLoadingFooter.setVisibility(View.GONE);
		    }
		}
	    } catch (JSONException e) {
		e.printStackTrace();
	    }
	}

	@Override
	public void onError(BzydroidHttpClient arg0,
		BzydroidNetworkExeception arg1) {
	    super.onError(arg0, arg1);
	    Debug.debug("onError");

	    if (!Util.isConnectingToInternet(ListVideoByPlaActivity.this)) {
		lvVideo.setVisibility(View.GONE);
		if (llLoading.getVisibility() == View.VISIBLE) {
		    llLoading.setVisibility(View.GONE);
		    llNotInternet.setVisibility(View.VISIBLE);
		}
	    } else {
		llNotInternet.setVisibility(View.GONE);
		lvVideo.setVisibility(View.VISIBLE);
	    }
	}

	@Override
	public void onFinished(BzydroidHttpClient arg0) {
	    super.onFinished(arg0);
	    Debug.debug("onFinished");
	    llLoading.setVisibility(View.GONE);
	    llLoadingFooter.setVisibility(View.GONE);
	}
    }

    private void loadMore() {
	if (requestVideoNew == null) {
	    requestVideoNew = new RequestVideoNew(ListVideoByPlaActivity.this,
		    clickTry);
	}
	RequestService.rqListVideoByPla(aId, String.valueOf(page), packageName,
		requestVideoNew);

    }

    private OnClickListener clickTry = new OnClickListener() {

	@Override
	public void onClick(View v) {
	    Debug.debug("clickTry Page : " + page);

	   loadMore();
	}
    };

    @Override
    public void onClick(View arg0) {
	switch (arg0.getId()) {
	case R.id.iv_search:
	    if (llContainEdt.getVisibility() == View.GONE) {
		llContainEdt.setVisibility(View.VISIBLE);
		ivABSearch.setVisibility(View.GONE);
		tvABTitle.setVisibility(View.GONE);
		edtABSearch.setFocusable(true);
		edtABSearch.requestFocus();
		showBoard(edtABSearch);
	    }
	    break;
	case R.id.iv_cancel:
	    String text = edtABSearch.getText().toString().trim();
	    if (!text.equals("")) {
		edtABSearch.setText("");
	    } else {
		llContainEdt.setVisibility(View.GONE);
		ivABSearch.setVisibility(View.VISIBLE);
		tvABTitle.setVisibility(View.VISIBLE);
		edtABSearch.setFocusable(true);
		hiddenBoard(edtABSearch);
	    }
	    break;
	}
    }

}
